package com.scuec.groupfive.controller;

import com.scuec.groupfive.entity.SystemSetting_six;
import com.scuec.groupfive.service.SystemSettingService_six;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/api/system")
@CrossOrigin


public class SystemSettingController_six {// 修改类名
    private static final String UPLOAD_DIR = "D:/uploads/";

    @Autowired
    private SystemSettingService_six systemSettingService;  // 修改注入的Service类型

    //http://localhost:8080/api/system/settings
    @GetMapping("/settings")
    public ResponseEntity<SystemSetting_six> getSystemSettings() {  // 修改返回类型
        SystemSetting_six setting = systemSettingService.getLatestSystemSetting();
        if (setting != null) {
            return ResponseEntity.ok(setting);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    //http://localhost:8080/api/system/update
    @PostMapping("/update")
    public int updateSystemSetting(@RequestBody SystemSetting_six systemSetting) {
        int result = systemSettingService.updateSystemSetting(systemSetting);
        return result;
    }


    // 文件上传接口
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 确保上传目录存在
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + fileExtension;

            // 保存文件到D:/uploads/
            Path filePath = uploadPath.resolve(newFilename);
            Files.copy(file.getInputStream(), filePath);

            // 返回文件URL
            String fileUrl = "/uploads/" + newFilename;
            return ResponseEntity.ok(fileUrl);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("文件上传失败: " + e.getMessage());
        }
    }
}